package com.netty.server;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * Netty服务端启动类
 * 
 * @author shengli.hu
 *
 */
@Slf4j
@Component
public class NettyServer {

	@Value("${netty.tcp.port}")
	private int port;

	@Value("${netty.boss.thread.count}")
	private int bossThreadCount;

	@Value("${netty.worker.thread.count}")
	private int workerThreadCount;

	@Value("${netty.so.keepalive}")
	private boolean soKeepalive;

	@Value("${netty.so.backlog}")
	private int soBacklog;

	@Value("${netty.log.level}")
	private String loglevel;

	/**
	 * 初始化处理
	 */
	@PostConstruct()
	public void init() {
		new Thread(new Runnable() {
			public void run() {
				startServer();
			}
		}).start();
	}

	/**
	 * Netty启动服务
	 */
	public void startServer() {
		log.info("【自定义】Netty服务start...");
		ChannelFuture channelFuture = null;
		//  boss处理客户端连接  work进行客服端连接之后的处理
		EventLoopGroup bossGroup = new NioEventLoopGroup(bossThreadCount);
		EventLoopGroup workerGroup = new NioEventLoopGroup(workerThreadCount);
		try {
			ServerBootstrap serverBootstrap = new ServerBootstrap();
			serverBootstrap.group(bossGroup, workerGroup);
			serverBootstrap.channel(NioServerSocketChannel.class);
			serverBootstrap.option(ChannelOption.SO_BACKLOG, soBacklog);
			serverBootstrap.handler(new LoggingHandler(loglevel));
			serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
			serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, soKeepalive);
			serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ChannelPipeline pipeline = ch.pipeline();
					pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
					pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
					pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
					// 自定义处理类（配置通道处理 来进行业务处理）
					pipeline.addLast(new NettyServerHandler());
				}
			});
			// 绑定端口,开始接收进来的连接
			channelFuture = serverBootstrap.bind(port).sync();

			log.info("【自定义】Netty服务start up on port: {} successfully!", port);
			// 等待服务器socket关闭
			channelFuture.channel().closeFuture().sync();
			log.info("【自定义】Netty服务close up on port: {} successfully!", port);
		} catch (Exception e) {
			log.error("【自定义】Netty服务启动异常：" + e.getMessage());
		} finally {
            //关闭资源
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
        }
	}

}
